<!DOCTYPE html>
<html>

<head>
  <title>签名功能示例</title>
  <style>
    #canvas {
      border: 1px solid #000;
      cursor: crosshair;
    }
  </style>
</head>

<body>
  <canvas id="canvas" width="400" height="200"></canvas>
  <button id="clearBtn">清除</button>
  <button id="saveBtn">保存</button>


</body>

</html>
<script>
  window.addEventListener('DOMContentLoaded', (event) => {
    const canvas = document.getElementById('canvas');
    const ctx = canvas.getContext('2d');
    let painting = false;
    let startPosition = { x: 0, y: 0 };

    function startDrawing(e) {
      painting = true;
      startPosition = getMousePosition(canvas, e);
    }

    function endDrawing() {
      painting = false;
    }

    function draw(e) {
      if (!painting) return;
      const currentPosition = getMousePosition(canvas, e);
      drawLine(startPosition.x, startPosition.y, currentPosition.x, currentPosition.y);
      startPosition = currentPosition;
    }

    function drawLine(x1, y1, x2, y2) {
      ctx.lineWidth = 2;
      ctx.lineCap = 'round';
      ctx.beginPath();
      ctx.moveTo(x1, y1);
      ctx.lineTo(x2, y2);
      ctx.stroke();
      ctx.closePath();
    }

    function getMousePosition(canvas, e) {
      const rect = canvas.getBoundingClientRect();
      return {
        x: e.clientX - rect.left,
        y: e.clientY - rect.top
      };
    }

    function clearCanvas() {
      ctx.clearRect(0, 0, canvas.width, canvas.height);
    }

    function saveSignature() {
      const dataURL = canvas.toDataURL();
      console.log(dataURL);
    }

    canvas.addEventListener('mousedown', startDrawing);
    canvas.addEventListener('mouseup', endDrawing);
    canvas.addEventListener('mousemove', draw);
    canvas.addEventListener('mouseleave', endDrawing);

    const clearBtn = document.getElementById('clearBtn');
    clearBtn.addEventListener('click', clearCanvas);

    const saveBtn = document.getElementById('saveBtn');
    saveBtn.addEventListener('click', saveSignature);
  });

</script>